By default, Algolia puts the most relevant items first in results. However, you might want to sort results by a specific attribute, like price or date.

To sort your search results by a specific attribute:

  1. Create a replica index
  2. Configure an attribute for sorting
  3. Update your user interface

Replica indices

Think of a replica index as a duplicate of your primary index but with a different sorting of results. Choose from two types of replicas: standard or virtual:

  • Use a standard replica for exhaustive sorting. This method sorts results by the chosen attribute.
  • Use a virtual replica for relevant sorting. This method prioritizes relevant results while still incorporating the sorting preference for the chosen attribute.

Configure an attribute for sorting in the Algolia dashboard

  1. Create a replica index.

  2. Refresh the dashboard page in your browser.

  3. Select the replica index.

  4. On the Configuration tab, go to Relevant sort or Ranking and Sorting. You’ll see either option, depending on the type of replica you want to configure (virtual or standard).

  5. Click +Add a sort attribute or +Add sort-by attribute

  6. Type in the name of the attribute you want to sort. Be careful here: Algolia doesn’t check to see if what you type matches the name of an attribute in the index.

  7. Determine the sort direction (Ascending or Descending).

  8. Review and save your changes.

Configure an attribute for sorting with the API

  1. Create a replica index.
  2. Update the ranking parameter of the replica index with the setSettings method.

Update user interface

To let users select between different rankings in your user interface, you also need to update it—for example, by providing a sort-by widget.

Example: relevant sort by price

This example applies relevant sorting to a virtual replica.

SearchIndex replica_index = client.InitIndex("products_virtual_price_desc");

IndexSettings settings = new IndexSettings { CustomRanking = new List<string> { "desc(price)" } };

// Synchronous
replica_index.SetSettings(settings);

// Asynchronous
await replica_index.SetSettingsAsync(settings);

For virtual replicas, you only need to include the customRanking attribute used for sorting: price.

Example: exhaustive sort by price

This example applies exhaustive sorting to a standard replica.

SearchIndex replica_index = client.InitIndex("products_standard_price_desc");

IndexSettings settings = new IndexSettings
{
    Ranking = new List<string>
    {
        "desc(price)",
        "typo",
        "geo",
        "words",
        "filters",
        "proximity",
        "attribute",
        "exact",
        "custom"
    }
};

// Synchronous
replica_index.SetSettings(settings);

// Asynchronous
await replica_index.SetSettingsAsync(settings);

For standard replicas, you need to provide all ranking attributes.